<template>
  <el-dialog
    v-model="dialogVisible"
    :title="titleStr"
    width="800"
    class="cjdzsex"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="分数" prop="score">
        <el-input
          v-model="ruleForm.score"
          style="width: 200px"
          @input="handleInput(ruleForm.score, 0)"
          :disabled="formType == 'checkRank' && isGKB == 1"
        />
        <div class="titleHeader">
          <el-icon>
            <InfoFilled />
          </el-icon>
          {{ hainan == true ? '分数区间 100-750' : '分数区间 100-900' }}
        </div>
      </el-form-item>
      <el-form-item label="语数外" prop="score_wx" v-if="isDzTypeDiff == 1">
        <el-input
          v-model="ruleForm.score_wx"
          style="width: 200px"
          @input="handleInput(ruleForm.score_wx, 3)"
          :disabled="formType == 'checkRank' && isGKB == 1"
        />
        <div class="titleHeader">
          <el-icon>
            <InfoFilled />
          </el-icon>
          分数区间 100-450
        </div>
      </el-form-item>

      <el-form-item
        :label="data.title"
        v-for="(data, index) in xkdata"
        :key="index"
        :prop="data.type == 1 ? 'radio' : 'checkbox'"
      >
        <el-radio-group
          v-if="data.type == 1"
          v-model="ruleForm.radio"
          :disabled="formType == 'checkRank' && isGKB == 1"
        >
          <el-radio
            :value="title"
            v-for="(id, title, index) in data.item"
            :key="index"
            >{{ title }}</el-radio
          >
        </el-radio-group>
        <el-checkbox-group
          v-else
          v-model="ruleForm.checkbox"
          :max="data.number * 1"
          :disabled="formType == 'checkRank' && isGKB == 1"
        >
          <el-checkbox
            :value="title"
            v-for="(id, title, index) in data.item"
            :key="index"
            >{{ title }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="位次" prop="position">
        <el-input
          v-model="ruleForm.position"
          style="width: 200px"
          @input="handleInput(ruleForm.position, 1)"
        />
        <el-button
          style="margin-left: 10px"
          type="primary"
          @click="queryPosition(ruleFormRef, '查询')"
        >
          查询
        </el-button>
        <el-select
          v-model="selectValue"
          class="m-2"
          style="width: 120px; margin-left: 10px"
          v-if="selectFlag"
          @change="selChange"
        >
          <el-option
            v-for="(item, index) in selectData"
            :label="item"
            :value="item"
          />
        </el-select>
        <div style="margin-left: 20px">{{ position }}</div>
      </el-form-item>

      <el-form-item class="btttn">
        <el-button @click="closeChange">取消</el-button>
        <el-button
          type="primary"
          class="ok"
          @click="submitForm(ruleFormRef, '提交')"
        >
          确定
        </el-button>
      </el-form-item>

      <el-form-item style="color: red" v-if="isGKB == '1'">
        <div style="font-size: 18px">
          高考版只能修改一次成绩信息，请谨慎修改！
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
  editUser,
  scoreStageInfo,
  scoreStageFilter,
} from '/src/api/appv2/appv2.js';

import xkType from '@/utils/xk_type.js';

const emits = defineEmits(['refreshStudentList', 'getTzyCount']);
const { proxy } = getCurrentInstance();

const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const provincelist = ref(JSON.parse(localStorage.getItem('provincelist')));

const formType = ref('');
//新增下拉框
const selectValue = ref('');
const selectData = ref([]);
const selectFlag = ref(false);

const isDzTypeDiff = ref(null); //判断省份
const ruleForm = reactive({
  score: '',
  position: '',
  score_wx: '',
  radio: '',
  checkbox: [],
});

const rules = reactive({
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!hainan.value == true) {
          if (value < 100 || value > 900) {
            callback(new Error('分数区间 100-900'));
          } else {
            callback();
          }
        } else {
          if (value < 100 || value > 750) {
            callback(new Error('分数区间 100-750'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur',
    },
  ],
  score_wx: [
    { message: '请输入语数外分数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 100 || value > 450) {
          callback(new Error('分数区间 100-450'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  radio: [{ required: true, message: '请选择科类', trigger: 'change' }],
  checkbox: [
    { required: true, message: '请选择科目', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error('请选择两个科目'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
});

// 父级传递的学生数据
const studentData = ref({});
const isGKB = ref('');
// 学生信息
const studentInfo = ref({});
const titleStr = ref('');
const xkdata = ref({}); // 选科科类信息
const position = ref(''); // 位次区间
const filterInfo = ref(null); // 筛选条件
const hainan = ref(true); //判断是否是海南
// 只允许输入数字 type 0-分数 1-位次
const handleInput = (score, type) => {
  if (type == 0) {
    ruleForm.score = score.replace(/[^\d]/g, '');
  } else if (type == 1) {
    ruleForm.position = score.replace(/[^\d]/g, '');
  } else {
    ruleForm.score_wx = score.replace(/[^\d]/g, '');
  }
};

const selChange = function (e) {
  console.log(e);

  getScoreStageInfo('查询');
};

// 查询位次
function queryPosition(formEl, text) {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      if (!filterInfo.value) {
        scoreStageFilter({
          studentId: studentData.value.studentId,
          pid: studentInfo.value.pid,
        }).then(async (res) => {
          console.log(res, '位次变化');
          filterInfo.value = res.data[0] || {};
          selectData.value = [];
          await getScoreStageInfo(text);
        });
      } else {
        await getScoreStageInfo(text);
      }
    }
  });
}

// 查询位次
function getScoreStageInfo(text) {
  const xk_type = studentInfo.value.xk_type;
  let course = '';
  var body = {
    studentId: studentData.value.studentId,
    pid: studentInfo.value.pid,
    year: filterInfo.value.year,
    score: ruleForm.score,
  };
  //判断上海类型  2
  if (xk_type == proxy.$XK_TYPE.T3_3) {
    const course = filterInfo.value.courses[0] || {};
    body['bzType'] = course.bzTypes[0] || '';

    if (selectData.value.length > 0 && !!selectValue.value) {
      if (course.bzTypes.includes(selectValue.value)) {
        body['bzType'] = selectValue.value;
      }
      if (isDzTypeDiff.value == 1 && body['bzType'].includes('专科')) {
        body['score'] = ruleForm.score_wx;
      }
    }
    body['course'] = course.course;
  } else {
    //判断非上海类型    1

    if (ruleForm.radio == '物理') {
      //判断单选 为物理时
      if (
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)
          .length > 0
      ) {
        course =
          filterInfo.value.courses.filter(
            (i) => i.course == ruleForm.radio
          )[0] || {};
      } else {
        course =
          filterInfo.value.courses.filter((i) => i.course == '理科')[0] || {};
      }
    } else if (ruleForm.radio == '历史') {
      if (
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)
          .length > 0
      ) {
        course =
          filterInfo.value.courses.filter(
            (i) => i.course == ruleForm.radio
          )[0] || {};
      } else {
        course =
          filterInfo.value.courses.filter((i) => i.course == '文科')[0] || {};
      }
    } else {
      course =
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)[0] ||
        {};
    }

    body['bzType'] = course.bzTypes[0] || '';
    if (selectData.value.length > 0 && !!selectValue.value) {
      if (course.bzTypes.includes(selectValue.value)) {
        body['bzType'] = selectValue.value;
      }
    }
    body['course'] = course.course;
  }

  if (selectData.value.length == 0) {
    filterInfo.value.courses.forEach((element) => {
      if (element['course'] == body['course']) {
        const bzTypes = element.bzTypes;
        if (bzTypes.length >= 2) {
          selectData.value = bzTypes;
          selectValue.value = selectData.value[0];
          selectFlag.value = true;
        }
      }
    });
  }

  scoreStageInfo(body).then((res) => {
    if (res.data.now_section.length == undefined) {
      position.value =
        '位次区间: ' +
        res.data.now_section.highestRank +
        '~' +
        res.data.now_section.lowestRank;
      ruleForm.position = res.data.now_section.lowestRank;
      geteditUserdata(text);
    } else {
      position.value = '';
      ruleForm.position = '';
      ElMessage({
        message: '未查询到位次区间',
        type: 'warning',
      });
    }
  });
}

// 提交表单

function submitForm(formEl, text) {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    setTimeout(async () => {
      if (valid) {
        console.log(text);
        // if (!ruleForm.position) {
        //   await queryPosition(formEl, text);
        //   closeChange();
        // } else {
        geteditUserdata(text); //原本就掉这里 现在改成先查询位次在调接口
        // }
      }
    }, 1000);
  });
}

//
const geteditUserdata = (text) => {
  let xkInfos = {};
  xkdata.value.forEach((item) => {
    xkInfos = { ...xkInfos, ...item.item };
  });

  let xkIds = [];
  ruleForm.checkbox.forEach((item) => {
    xkIds.push(xkInfos[item]);
  });

  if (ruleForm.radio.length > 0) {
    // 单独把单选的加进去
    xkIds.push(xkInfos[ruleForm.radio]);
  }

  xkIds = [...new Set(xkIds)];

  let data = {};
  data['studentId'] = studentData.value.studentId;
  data['score'] = ruleForm.score;
  data['section'] = ruleForm.position;
  data['score_wx'] = ruleForm.score_wx;
  data['sgid'] = xkIds.toString();
  data['fronttype'] = 3;
  if (text != '查询') {
    editUser(data).then(() => {
      emits('refreshStudentList', {});
      emits('getTzyCount', {});
      closeChange();
    });
  }
};

function closeChange() {
  dialogVisible.value = false;
}

function openChange(val, type) {
  // selectValue.value = selectData.value[0]
  selectFlag.value = false;
  selectData.value = [];
  formType.value = type;
  if (type == 'checkRank') {
    for (const key in ruleForm) {
      if (val.student.hasOwnProperty(key)) {
        ruleForm[key] = val.student[key];
      }
    }
  }

  if (val.gkaProvinceName == '海南') {
    hainan.value = false;
  } else {
    hainan.value = true;
  }
  provincelist.value.forEach((item) => {
    if (item.provinceName == val.gkaProvinceName) {
      isDzTypeDiff.value = item.isDzTypeDiff;
    }
  });

  // isGKB.value = isGkData.isGKB
  isGKB.value = val.isGKB;
  dialogVisible.value = true;
  studentData.value = val;
  studentInfo.value = val.student;
  titleStr.value =
    '成绩-' +
    val.studentName +
    '-' +
    val.student.province +
    '-' +
    (val.student.sex == 0 ? '男' : '女');
  if (type != 'checkRank') {
    ruleForm.score = '';
    ruleForm.position = '';
    ruleForm.radio = '';
    ruleForm.checkbox = [];
    ruleForm.score_wx = '';
    position.value = '';
  }

  filterInfo.value = null;

  // 新疆地区
  if (val.student.xk_type == 1) {
    xkdata.value = [
      {
        type: '1', // 1-单选，2-多选
        title: '选考科目',
        item: {
          文科: '22',
          理科: '11',
        },
      },
    ];
    if (type == 'checkRank') {
      ruleForm.radio = val.student.sgid
        .split(',')
        .map(Number)
        .map((code) => xkType.subjectCodeMode[code])[0];
    }
  }
  //  山东地区
  else if (val.student.xk_type == 2) {
    xkdata.value = [
      {
        type: '2',
        number: '3',
        title: '选考科目',
        item: {
          物理: '1',
          化学: '2',
          生物: '3',
          政治: '6',
          历史: '4',
          地理: '5',
        },
      },
    ];
    if (type == 'checkRank') {
      ruleForm.checkbox = val.student.sgid
        .split(',')
        .map(Number)
        .map((code) => xkType.subjectCodeMode[code]);
    }
  }
  // 江苏地区
  else {
    xkdata.value = [
      {
        // 单选
        type: '1',
        title: '首选科目',
        item: {
          物理: '1',
          历史: '4',
        },
      },
      {
        // 双选
        type: '2',
        number: '2',
        title: '再选科目',
        item: {
          化学: '2',
          生物: '3',
          政治: '6',
          地理: '5',
        },
      },
    ];
    if (studentInfo.value.pid == '33') {
      // 省ID=33 浙江7选3
      xkdata.value[0]['item']['技术'] = '7';
    }

    if (type == 'checkRank') {
      const codes = (val.student?.sgid || '')
        .split(',')
        .map(Number)
        .filter((n) => !isNaN(n));

      // 定义需要特殊处理的科目代码
      const SPECIAL_CODES = [1, 4];

      // 找出第一个特殊科目
      const specialSubject = codes.find((code) => SPECIAL_CODES.includes(code));

      // 设置radio（优先取特殊科目，若无则取第一个科目，若无则空）
      ruleForm.radio = specialSubject
        ? xkType.subjectCodeMode[specialSubject]
        : codes[0]
          ? xkType.subjectCodeMode[codes[0]]
          : '';

      // 设置checkbox（排除已用于radio的科目）
      ruleForm.checkbox = codes
        .filter((code) => code !== specialSubject)
        .map((code) => xkType.subjectCodeMode[code])
        .filter(Boolean);
    }
  }
}

// 暴露方法
defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped>
.titleHeader {
  display: flex;
  align-items: center;
  background-color: #f4f4f5;
  color: #909399;
  margin-left: 20px;
  padding: 0 8px;
}
</style>
<style lang="scss">
.cjdzsex {
  padding: 0 !important;
  .el-dialog__header {
    min-height: 66px;
    padding: 19px 30px;
    margin: 0;
  }
  .el-dialog__body {
    padding: 24px 24px 16px 24px;
  }

  .btttn {
    .el-form-item__content {
      margin: 0 !important;
      justify-content: end;
      .el-button {
        width: 70px;
        height: 40px;
      }
      .ok {
        background-color: var(--primary-color);
        &:hover {
          background-color: var(--primary-hover-color);
        }
      }
    }
  }
}
</style>
